package com.bree.erp.service.stateless;

import java.util.Collection;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import com.bree.erp.entity.BrandSeller;
import com.bree.erp.service.BrandSellerService;

@Stateless
public class BrandSellerServiceBean implements BrandSellerService {

	@PersistenceContext()
	private EntityManager em;
	
	public BrandSellerServiceBean() {
		
	}
	
	public BrandSellerServiceBean(EntityManager em) {
		this.em = em;
	}

	@Override
	public BrandSeller create(String name, String description) {
		BrandSeller seller = new BrandSeller();
		
		seller.setName(name);
		seller.setDescription(description);
		
		em.persist(seller);
		
		return seller;
	}

	@Override
	public BrandSeller read(Long id) {
		
		return em.find(BrandSeller.class, id);
	}

	@Override
	public BrandSeller update(Long id, String name, String description) {

		BrandSeller seller = read(id);
		
		seller.setName(name);
		seller.setDescription(description);
		
		return seller;
	}

	@Override
	public void delete(Long id) {
		
		BrandSeller seller = read(id);
		
		em.remove(seller);
		
	}

	@Override
	public Collection<BrandSeller> list() {
		
		TypedQuery<BrandSeller> query = em.createNamedQuery(BrandSeller.QUERY_SELECT_ALL_BRANDSELLER, BrandSeller.class);
		
		return query.getResultList();
	}

	@Override
	public BrandSeller findByName(String name) {
		TypedQuery<BrandSeller> query = em.createNamedQuery(BrandSeller.QUERY_FINDBYNAME_BRANDSELLER, BrandSeller.class)
				.setParameter("name", name);
		
		try {
			return query.getSingleResult();
		} catch(NoResultException e) {
			return null;
		}
		
	}

}
